package org.geektimes.projects.user.web.listener;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

import static org.geektimes.utils.ThreadLocalData.threadLocalConfig;

public class ConfigRequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        threadLocalConfig.remove();
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        final ServletRequest servletRequest = sre.getServletRequest();
        final String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();
        //排除静态资源
        if(!requestURI.matches(".+\\.(js|css|ico|icon)$")){
            final ServletContext servletContext = sre.getServletContext();
            final ClassLoader classLoader = servletContext.getClassLoader();
            final ConfigProviderResolver instance = ConfigProviderResolver.instance();
            final Config config = instance.getConfig(classLoader);
            //Config config = (Config)servletContext.getAttribute("microConfig");
            threadLocalConfig.set(config);
        }
    }



}
